// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  let { OPENID, APPID, UNIONID } = wxContext
  let { nickName } = event
  var success = false
  var message = "申请教练失败，请联系管理员"
  var resp = {}
  const db = cloud.database()
  var res = await db.collection('coach').where({
    _openid: OPENID
  }).get()

  if (res.data.length != 0) {
    success = false
    message = "申请教练失败，请勿重复申请"
  } else {
    var addResp = await db.collection('coach').add({
      data: {
        _openid: OPENID,
        nickName: nickName
      }
    }).then(res => {
      console.log("update:", res)
      success = true
      message = "申请教练成功，请联系管理员审核"
    }, error => {
      success = false
      message = "申请教练失败，请联系管理员"
    })
  }
  return {
    success: success,
    message: message,
    data: resp
  }

}